import { constantRoutes } from '@/router'

export const hasChild = item => {
  return item.children && item.children.length !== 0
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, menu) {
  const res = []

  menu.forEach(route => {
    const obj = {
      icon: route.iconPath,
      name: route.url,
      meta: {
        title: route.menuDescriptions[0].description
      }
    }
    if (hasChild(route)) {
      obj.children = filterAsyncRoutes(route.children, menu)
    }
    res.push(obj)
  })
  const arr = [...routes, res]
  return arr
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, menu) {
    return new Promise(resolve => {
      // let accessedRoutes
      // if (menu) {
      //   accessedRoutes = []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(accessedRoutes, menu)
      // }
      commit('SET_ROUTES', menu)
      resolve(menu)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
